package com.erik.lin.test.script;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.*;

/**
 * Created by Erik on 2017/5/25.
 */
public class JsStep {

    private static Logger LOG = LoggerFactory.getLogger(JsStep.class);

    public static void main(String[] args) throws ScriptException {
        ScriptEngine engine = builderScriptEngine();
        String script = "var f = 100.0; var s=f.toString(); var ss=s.substring(s.indexOf('.')); return Number(ss)";
        CompiledScript jsFunc1 = scriptCompile(engine,script);
        Object so = jsFunc1.eval();
        System.out.print(so);
    }

    public static ScriptEngine builderScriptEngine() {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = null;
        try {
            engine = sem.getEngineByName("nashorn");
            if (engine == null) {
                LOG.warn("创建nashorn引擎失败，需要使用JDK 8。启用Rhino引擎，会导致性能下降并且语法不兼容");
                engine = sem.getEngineByName("JavaScript");
            }
        } catch (Exception e) {
            LOG.warn("创建nashorn引擎失败，需要使用JDK 8。启用Rhino引擎，{}会导致性能下降并且语法不兼容", e.getMessage());
            engine = sem.getEngineByName("JavaScript");
        }
        return engine;
    }

    public static CompiledScript scriptCompile(ScriptEngine engine,String script) throws ScriptException {
        Compilable compilable = (Compilable) engine;
        StringBuilder sb = new StringBuilder();
        sb.append("(function(){\r\n\r\n").append(script).append("\r\n\r\n})()");
        CompiledScript jsFunc1 = compilable.compile(sb.toString());
        return jsFunc1;
    }
}
